//
//  NoteTestVC.m
//  MovieDate
//
//  Created by ann on 16/3/14.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "NoteTestVC.h"
#import "RegisterDataVC.h"
#import "AFNetworking.h"
#import "UserProtcolViewController.h"

@interface NoteTestVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *noteTestBorderStyle1;
@property (weak, nonatomic) IBOutlet UIView *noteTestBorderStyle2;
@property (weak, nonatomic) IBOutlet UITextField *numberTXF;
@property (weak, nonatomic) IBOutlet UITextField *testCodeTXF;

@property (weak, nonatomic) IBOutlet UIButton *nextBTN;
@property (weak, nonatomic) IBOutlet UIButton *sendTestCode;
@property (weak, nonatomic) IBOutlet UIButton *didHaveNumberBTN;

@property (weak, nonatomic) IBOutlet UIButton *protcolBTN;
@end

@implementation NoteTestVC



- (void)viewDidLoad {
    [super viewDidLoad];
    [self initViewTxFBorderStyle];
  
    
    // Do any additional setup after loading the view from its nib.
}

-(void)initViewTxFBorderStyle{
    self.noteTestBorderStyle1.layer.borderWidth = 1;
    self.noteTestBorderStyle2.layer.borderWidth = 1;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
    
    [self initView];

}

-(void)initView{

    [self selDefaultNavigationBackground];
    [self selDefaultNavigationWithTitle:@"短信验证"];
    [self selAddLeftBackButton];
    
    
    self.testCodeTXF.delegate = self;
    [self.sendTestCode addTarget:self action:@selector(clickSendCodeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.sendTestCode setSelected:YES];
     self.sendTestCode.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
    
    [self.protcolBTN setTitleColor:[UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1] forState:(UIControlStateNormal)];
      [self.protcolBTN setTitleColor:[UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1] forState:(UIControlStateHighlighted)];
    [self.didHaveNumberBTN setTitleColor: [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1]forState:(UIControlStateNormal)];
    [self.didHaveNumberBTN setTitleColor:[UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1] forState:(UIControlStateHighlighted)];
    self.nextBTN.userInteractionEnabled = NO;
    
}

-(void)clickSendCodeAction:(UIButton *)btn{
    NSString *numb = [self valiMobile:self.numberTXF.text];
    
    if (numb.length == 11) {
        
     
     [TDNetwork sendDynCodePostURL:sendDynCodeIP andPhoneNumber:self.numberTXF.text andType:@"1" complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
       
         if ([ret isEqualToString:@"1"]){
             
             self.nextBTN.userInteractionEnabled = YES;
             self.nextBTN.backgroundColor =[UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
             
         }else if ([ret isEqualToString:@"-1"]){
                 [SVProgressHUD showInfoWithStatus:@"账号已经存在"];
     
             
         }else{
             [SVProgressHUD showInfoWithStatus:@"不存在这个账号"];
         }
     }];
        self.sendTestCode.backgroundColor = [UIColor grayColor];
        __block int timeout = 60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.sendTestCode setTitle:@"获取验证码" forState:UIControlStateNormal];
                    self.sendTestCode.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
                    self.sendTestCode.userInteractionEnabled = YES;
                });
            }else{
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1];
                    [self.sendTestCode setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    
                    self.sendTestCode.userInteractionEnabled = NO;
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
    }
    
}


//验证码输入框结束编辑的时候
- (void)textFieldDidEndEditing:(UITextField *)textField{


}
- (void)textFieldDidBeginEditing:(UITextField *)textField{


}

- (IBAction)clickDidHaveNumb:(id)sender {
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (IBAction)clickNextBTN:(id)sender {
      __weak typeof(self) weakSelf = self;
    [SVProgressHUD show];
     [TDNetwork testDynCodePostURL:testCodeIP andPhoneNumber:self.numberTXF.text andCode:self.testCodeTXF.text complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            RegisterDataVC *regisVC =    [[RegisterDataVC alloc]init];
         
         if (succeed) {
             
             switch ([ret intValue]) {
                 case 1:
                     [SVProgressHUD dismiss];
                     regisVC.token = [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]]; //随机数验证码
                     regisVC.PhoneNumber = weakSelf.numberTXF.text;
                     [weakSelf.navigationController pushViewController:regisVC animated:YES];
                     break;
                     
                  case -1:
                     [SVProgressHUD showErrorWithStatus:@"账号已经注册"];
                  
                     break;
                    case -2:
                     [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                  
                     break;
                     
                    case -3:
                     [SVProgressHUD showErrorWithStatus:@"验证码超过3分钟"];
               

                     break;
                  case -4:
                     [SVProgressHUD showErrorWithStatus:@"手机号或者验证码（为空）不正确"];
              
                     
                     break;
                 default:
                     [SVProgressHUD showErrorWithStatus:@""];
                     break;
             }
         }else{
             [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                [SVProgressHUD dismiss];
         }
         }];
}
- (IBAction)clickUserProtocol:(id)sender {
        UserProtcolViewController *protcol = [[UserProtcolViewController alloc]init];
    [self.navigationController pushViewController:protcol animated:NO];
}



//判断是否是手机号
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        [SVProgressHUD showErrorWithStatus:@"手机号码位数错误"];
        
        return @"手机号11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return mobile;
        }else{
           
            [SVProgressHUD showInfoWithStatus:@"请输入正确的手机号码"];
            return @"请输入正确";
        }
    }
    return nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
